/**
 * Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * @file sts_token_manager.js
 * @author leeight
 */

var Q = require('./vendor/q');
var utils = require('./utils');
/**
 * StsTokenManager
 *
 * @constructor
 * @class
 * @param {Object} options The options.
 */
function StsTokenManager(options) {
    this.options = options;

    this._cache = {};
}

StsTokenManager.prototype.get = function (bucket) {
    var self = this;

    if (self._cache[bucket] != null) {
        return self._cache[bucket];
    }

    return Q.resolve(this._getImpl.apply(this, arguments)).then(function (payload) {
        self._cache[bucket] = payload;
        return payload;
    });
};

StsTokenManager.prototype._getImpl = function (bucket) {
    var options = this.options;
    var uptoken_url = options.uptoken_url;
    var timeout = options.uptoken_timeout || options.uptoken_jsonp_timeout;
    var viaJsonp = options.uptoken_via_jsonp;
    var deferred = Q.defer();
    wx.request({
        url:uptoken_url,
        dataType:'json',
        data:{
          sts: JSON.stringify(utils.getDefaultACL(bucket))
        },
        header:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'POST',
        success:function(payload){
          var data = payload.data;
          if(data && typeof data === 'object'){
              if (data['AccessKeyId'] 
                  && typeof data['AccessKeyId'] === 'string'
                  && data['SecretAccessKey'] 
                  && typeof data['SecretAccessKey'] === 'string'
                  && data['SecretAccessKey'] 
                  && typeof data['SessionToken'] ==='string'){
                  deferred.resolve(data);
              }else if(data['result'] && typeof data['result'] === 'object'){
                  var result = data['result'];
                  if (result['AccessKeyId']
                      && typeof result['AccessKeyId'] === 'string'
                      && result['SecretAccessKey']
                      && typeof result['SecretAccessKey'] === 'string'
                      && result['SecretAccessKey']
                      && typeof result['SessionToken'] === 'string') {
                      deferred.resolve(result);
                  }
              }else{
                 deferred.reject(new Error('Get sts token fail'));
              }
          }else{
            deferred.reject(new Error('Get sts token fail'));
          }
        },
        fail:function(){
          deferred.reject(new Error('Get sts token timeout (' + timeout + 'ms).'));
        }
    });
    return deferred.promise;
};

module.exports = StsTokenManager;
